package com.example.readxml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.bean.News;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ActionBarActivity {
	  ListView vlist=null;
      List<Map<String, String>> data1=null;
      
      Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
            if (msg.what==0x1123) {
				String[] itemname={"id","title","linkaddr","timelen"};
				int[] itemid={R.id.vid,R.id.vtitle,R.id.linkaddr,R.id.timelen};
				SimpleAdapter adapter=new SimpleAdapter(getApplicationContext(), data1, R.layout.item, itemname, itemid);
				vlist.setAdapter(adapter);
			}
		}};
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		vlist=(ListView) findViewById(R.id.vlist);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					showdata();
					Log.i("MainActivity", data1.size() +"");
					handler.sendEmptyMessage(0x1123);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}).start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void showdata() throws Exception{
		data1=new ArrayList<Map<String, String>>();
		List<News> newses=NewsOp.getNewsList();
		for(News news:newses){
			Map<String, String> item = new HashMap<String, String>();
			item.put("id", news.getId());
			item.put("title", news.getTitle());
			item.put("linkaddr", news.getLinkaddr());
			item.put("timelen", news.getTimelen()+"");
			data1.add(item);
		}
	}
	
}
